package com.brave.mvvm.mvvmhelper.utils

import com.blankj.utilcode.util.Utils
import com.brave.mvvm.mvvmhelper.R

/**
 * ***author*** ：brave tou
 *
 * ***data***   : 2021/9/1 16:07
 *
 * ***desc***   : 路径工具
 */

/**
 * 获取Url的指定参数
 */
fun Any?.getParamByUrl(key: String): String {
    if (null == this) return ""
    val url = "$this"
    val length = url.length
    if (length <= 0) return ""
    val index: Int = url.indexOf("?")
    val temp: String = if (index >= 0) url.substring(index + 1) else url
    val keyValue =
        temp.split(Utils.getApp().getString(R.string.str_and_symbols).toRegex()).toTypedArray()
    val destPrefix: String = "$key="
    for (str in keyValue) {
        if (str.indexOf(destPrefix) == 0) {
            return str.substring(destPrefix.length)
        }
    }
    return ""
}

/**
 * 获取Url的参数集
 */
fun Any?.getParamMap(): MutableMap<String, String> {
    val map = mutableMapOf<String, String>()
    if (null == this) return map
    val url = "$this"
    val length = url.length
    if (length <= 0) return map
    val index: Int = url.indexOf("?")
    val temp: String = if (index >= 0) url.substring(index + 1) else url
    val app = Utils.getApp()
    val keyValue =
        temp.split(app.getString(R.string.str_and_symbols).toRegex()).toTypedArray()
    for (str in keyValue) {
        val indexOf = str.indexOf(app.getString(R.string.str_equal_symbols))
        if (indexOf != -1) {
            map[str.substring(0, indexOf)] = str.substring(indexOf + 1)
        }
    }
    return map
}

/**
 * 为Url拼接参数
 */
fun Any?.jointParam(map: MutableMap<String, Any>? = null): String {
    if (null == this) return ""
    var url = "$this"
    if (null == map) return url
    var param = ""
    map.forEach { (t, u) ->
        // 获取链接中对应参数的值
        val value = url.getParamByUrl(t)
        // 参数值是否存在
        if (value.isEmpty()) {
            // 不存在则拼接参数
            param += "&${t}=${u}"
        } else {
            // 存在则替换参数
            url = url.replace("${t}=${value}", "${t}=${u}")
        }
    }
    if (param.isNotEmpty()) {
        param = param.substring(1)
    }
    return if (url.indexOf("?") == -1) {
        "${url}?${param}"
    } else {
        "${url}&${param}"
    }
}